package com.xinli.xinlifm.view.fragment.find;

import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.xinli.xinlifm.App;
import com.xinli.xinlifm.R;
import com.xinli.xinlifm.http.bean.find.FindXinChangBean;
import com.xinli.xinlifm.mvp.model.SuperModel;
import com.xinli.xinlifm.sql.XinLiSqlHelper;
import com.xinli.xinlifm.view.activity.player.PlayerActivity;
import com.xinli.xinlifm.view.adapter.find.FindSecondRecyclerAdapter;
import com.xinli.xinlifm.view.fragment.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;


/**
 * Created by zz on 16-10-13.
 */

public class FindSecondFragment extends BaseFragment<SuperModel> implements View.OnClickListener, PtrHandler, FindSecondRecyclerAdapter.OnChildItemListener {
    private RecyclerView secondRecyclerView;
    private ImageView coverImageView;
    private PtrClassicFrameLayout ptrFrameLayout;
    private LinearLayout layoutDownload;
    private String tag;
    private FindSecondRecyclerAdapter findSecondListAdapter;
    private int offset =0;
    private int limit = 10;
    private boolean isLoading =true;

    public static FindSecondFragment newInstance(String tag,int type) {

        Bundle args = new Bundle();
        args.putString("tag",tag);
        args.putInt("type",type);
        FindSecondFragment fragment = new FindSecondFragment();
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public SuperModel getModel() {
        return new SuperModel();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        View view = inflater.inflate(R.layout.fragment_second_list, container, false);
        initView(view);
        initEvent();

        tag = getArguments().getString("tag");

        findSecondListAdapter = new FindSecondRecyclerAdapter(getActivity(), new ArrayList<FindXinChangBean.DataBean>());
        secondRecyclerView.setAdapter(findSecondListAdapter);
        Log.e("自定义标签", "类名==FindSecondFragment" + "方法名==onCreateView=====:" + tag);
        SQLiteDatabase db = App.xinLiSqlHelper.getWritableDatabase();
        Cursor cursor = db.query("cache",null , "page=?", new String[]{tag}, null, null, null);
        if (cursor.moveToFirst()) {
            String string = cursor.getString(1);
            String string2 = cursor.getString(2);
            long thisTime = System.currentTimeMillis();
            Log.e("自定义标签", "类名==FindSecondFragment" + "方法名==onCreateView=====:" + string2);
            long lastTime = Long.parseLong(string2);
            if(thisTime<lastTime+20*60*60){ //20 分钟
                FindXinChangBean changBean = new Gson().fromJson(string, FindXinChangBean.class);
                findSecondListAdapter.addAll(changBean.getData());

            }else {
                getModel().getFindXinChang(tag,0);
            }
        }else {
            getModel().getFindXinChang(tag,0);
        }
        TextView textView = (TextView) view.findViewById(R.id.find_second_title);
        textView.setText(tag);


        return view;
    }

    private void initEvent() {
        coverImageView.setOnClickListener(this);
        secondRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            int lastVisibleItem;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.e("自定义标签", "类名==OnRecyclerScrollListener" + "方法名==onScrollStateChanged===crr==:" + newState);
                if (!isLoading&&findSecondListAdapter!= null && newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem+2>=
                        findSecondListAdapter.getItemCount()) {
                    Log.e("自定义标签", "类名==FindSecondFragment" + "方法名==onScrollStateChanged=====:" + findSecondListAdapter.getItemCount());
                    if(offset >= 70){
                        findSecondListAdapter.setLastShow(2);
                        return;
                    }
                    offset = offset +10;
                    isLoading =true;
                    Log.e("自定义标签", "类名==FindSecondFragment" + "方法名==onScrollStateChanged=====:" + offset);
                    getModel().getFindXinChang(tag,offset);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition();
                Log.e("自定义标签", "类名==FindSecondFragment" + "方法名==onScrolled=====:" + lastVisibleItem);
            }
        });
    }

    private void initView(View view) {
        secondRecyclerView = ((RecyclerView) view.findViewById(R.id.find_second_list));
        secondRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        ptrFrameLayout = ((PtrClassicFrameLayout) view.findViewById(R.id.ptr_frameLayout));
        coverImageView = ((ImageView) view.findViewById(R.id.find_second_back));
        ptrFrameLayout.setPtrHandler(this);
        layoutDownload = ((LinearLayout) view.findViewById(R.id.find_second_ll_download));

    }


    @Subscribe
    public void showFindXinView(FindXinChangBean findXinChangBean){
        isLoading =false;
        ptrFrameLayout.refreshComplete();
        List<FindXinChangBean.DataBean> dataBeanList = findXinChangBean.getData();
        findSecondListAdapter.addAll(dataBeanList);

        layoutDownload.setVisibility(View.INVISIBLE);

        SQLiteDatabase db = App.xinLiSqlHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("page",tag);
        values.put("content",new Gson().toJson(findXinChangBean));
        values.put("time",System.currentTimeMillis());
        db.insert("cache", null, values);

        findSecondListAdapter.setOnChildItemListener(this);


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * imageView中的布局
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.find_second_back:
                getActivity().finish();
                break;
        }
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
    }

    /**
     * 做耗时操作后更新UI
     * @param frame
     */
    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        Log.e("自定义标签", "类名==FindSecondFragment" + "方法名==onRefreshBegin=====:" + "frame");
        getModel().getFindXinChang(tag,0);
        findSecondListAdapter.clear();
    }

    @Override
    public void onChildItemListener(FindXinChangBean.DataBean dataBean, int position) {
//        Toast.makeText(getActivity(), ""+position, Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(getActivity(), PlayerActivity.class);
        intent.putExtra("id",dataBean.getId()+"");
        getActivity().startActivity(intent);
    }
}
